home *** CD-ROM | disk | FTP | other *** search
/ Magnum One / Magnum One (Mid-American Digital) (Disc Manufacturing).iso / d12 / ecstr2.arc / STRFIND.C < prev    next >
C/C++ Source or Header  |  1987-03-04  |  2KB  |  50 lines

  1. /*  File   : strfind.c
  2.     Author : Richard A. O'Keefe.
  3.     Updated: 23 April 1984
  4.     Defines: strfind()
  5.  
  6.     strfind(src, pat) looks for an instance of pat in src.  pat is not a
  7.     regex(3) pattern, it is a literal string which must be matched exactly.
  8.     As a special hack to prevent infinite loops, the empty string will be
  9.     found just once, at the far end of src.  This is hard to justify.  The
  10.     result is a pointer to the first character AFTER the located instance,
  11.     or NullS if pat does not occur in src.  The reason for returning the
  12.     place after the instance is so that you can count the number of instances
  13.     by writing
  14.        _str2pat(ToBeFound);
  15.        for (p = src, n = 0; p = strfind(p, NullS); n++) ;
  16.     If you want a pointer to the first character of the instance, it is up
  17.     to you to subtract strlen(pat).
  18.  
  19.     If there were a strnfind it wouldn't have to look at all the characters
  20.     of src, this version does otherwise it could miss the closing NUL.
  21. */
  22.  
  23. #include "strings.h"
  24. #include "_str2pat.h"
  25.  
  26. char *strfind(src, pat)
  27.     char *src, *pat;
  28.     {
  29.        register char *s, *p;
  30.        register int c, lastch;
  31.  
  32.        pat = _str2pat(pat);
  33.        if (_pat_lim < 0) {
  34.            for (s = src; *s++; ) ;
  35.            return s-1;
  36.      }
  37.        /*  The pattern is non-empty  */
  38.        for (c = _pat_lim, lastch = pat[c]; ; c = _pat_vec[c]) {
  39.            for (s = src; --c >= 0; )
  40.                if (!*s++) return NullS;
  41.            c = *s, src = s;
  42.            if (c == lastch) {
  43.                for (s -= _pat_lim, p = pat; *p; )
  44.                    if (*s++ != *p++) goto not_yet;
  45.                return s;
  46. not_yet:;   }
  47.        }
  48.     }
  49.  
  50.